/**
 * 新的home
 */
import React, {Component} from 'react';
import {View, StyleSheet, Text, ListView, TouchableOpacity,RefreshControl, Platform,Image,ActivityIndicator, Modal,
    TouchableHighlight} from  'react-native';
import Mock from 'mockjs';
import Icon from 'react-native-vector-icons/FontAwesome';
import EasyList from 'react-native-easy-listview-gridview';
import HomeHeadView from './HomeHeadView';
import ChooseCity from './ChooseCity';
import area from '../../Data/area.json';
import Picker from 'react-native-picker';
import {Geolocation} from  'react-native-baidu-map';
import SearchBar from 'react-native-searchbar';
import {LinesLoader} from 'react-native-indicator';
import GoodDetail from './GoodDetail';
let dimension = require('Dimensions');
let {width, height} = dimension.get('window');
let that;
export default class Home extends Component {
    constructor(props) {
        super(props);
        this.state={
            content:'',
            modalVisible:false,
            animationType:'none',
            city:'广西南宁西乡塘区',
            items:[],
            results: []
        };
        this.startGeolocation=this.startGeolocation.bind(this);
        this._handleResults = this._handleResults.bind(this);
        this._focus1 = this._focus1.bind(this);
        this._closeModal = this._closeModal.bind(this);
        this._onFetch = this._onFetch.bind(this);
        this.getAllGoods=this.getAllGoods.bind(this);
        that=this;
    }
    componentWillMount() {
        this.startGeolocation();

    }
    startGeolocation(){
        Geolocation.getCurrentPosition()
            .then(data=>{
                let addressText='';
                if (data.province!=''&&data.province!=null) {
                    let pro = data.province.slice(0, 2);
                    addressText=pro+data.city+data.district

                }
                else {
                    addressText='未知位置'
                }
                this.setState({city:addressText})
            })
            .catch(e =>{
                this.setState({city:'定位失败'})
            })
    }

    getAllGoods(){
        let url="http://rapapi.org/mockjs/18259/api/getAllGoods?userId=654654";
        fetch(url)
            .then((response) => response.json())
            .then((responseData) => {
                let data = Mock.mock(responseData);
                if (data.success) {
                    let item = data.data;
                    let goodNames=[];
                    for (let i=0;i<item.length;i++){
                        goodNames.push(item[i].goodName)
                    }
                    this.setState({items:goodNames})
                }
            })
            .catch((error) => {

            })
    }

    render() {
        return (
            <View style={styles.container}>
                {this.renderNavBar()}
                <EasyList
                    renderHeader={this.renderHeaderView}
                    ref={component => this.listview = component}
                    renderItem={this.renderRow}
                    column={2}
                    dataSizePerPage={20}
                    refreshHandler={this._onFetch}
                    loadMoreHandler={this._onFetch}
                    renderFooterNoMore={this.renderFooterNoMore}
                    renderFooterError={this.renderFooterError}
                    renderFooterLoading={this.renderFooterLoading}
                    loadFailContent="加载出错，请检查网络"

                />
                <Modal
                    animationType="fade"
                    visible={this.state.modalVisible}
                    onRequestClose={() => {this._setModalVisible(false)}}
                >
                    <View style={{ marginTop: 80 }}>
                        {
                            this.state.results.map((result, i) => {
                                return (
                                    <View style={{borderBottomWidth:1,borderBottomColor:'#e8e8e8'}} key={i}>
                                    <Text style={{fontSize:20,margin:10}}>
                                        {typeof result === 'object' && !(result instanceof Array) ? 'gold object!' : result.toString()}
                                    </Text>
                                    </View>
                                );
                            })
                        }
                    </View>
                    <SearchBar
                        ref={(ref) => this.searchBar = ref}
                        data={this.state.items}
                        handleResults={this._handleResults}
                        showOnLoad
                        placeholder="搜索好喝的酒"
                        onBack={this._closeModal}
                    />
                </Modal>
            </View>
        )
    }
    _handleResults(results) {
        //参照大部分app，只取搜索结果前十条记录
        let needLength=9;
        if (results.length>10){
            results.splice(needLength,results.length-(needLength+1))
        }
        this.setState({ results });
    }
    renderHeaderView(){
        // let {navigator} = that.props;
        return(
            <HomeHeadView navigator={that.props.navigation} popTopHome={(componentName,param)=>that.openComment(componentName,param)}/>
        )
    }
    renderRow(index,rowData) {
        let viewMarginLeft;
        let viewMarginRight;
        let viewMarginTop=1;
        let viewMarginBottom=1;
        let goodsName=rowData.goodsName;
        let goodsPrice=rowData.goodsPrice;
        let buyTotal=rowData.buyTotal;
        let param={title:goodsName};
        let url='https://h5.youzan.com/v2/goods/3nhu8ptov31m2?reft=1496974798633&spm=f44930604';
        if (index%2==1){
            viewMarginRight =2 ;
            viewMarginLeft = 1;
        }
        else {
            viewMarginLeft = 2;
            viewMarginRight = 1;
        }
        return (
            <View style={[styles.listViewStyle,{marginLeft:viewMarginLeft,marginRight:viewMarginRight,marginTop:viewMarginTop,marginBottom:viewMarginBottom}]} key={index}>
                <TouchableOpacity  onPress={()=>that.openComment('GoodDetail',param)} >
                    <Image resizeMode='stretch' source={{uri:rowData.goodsImage}} style={styles.imageStyle}/>
                    <Text style={{fontSize:16}}>{rowData.goodsName}</Text>
                    <View style={{justifyContent:'space-between',flexDirection:'row'}}>
                        <Text style={{fontSize:12,color: 'red'}}>{rowData.goodsPrice}</Text>
                        <Text style={{fontSize:11,color:'#585858'}}>{rowData.buyTotal}</Text>
                    </View>
                </TouchableOpacity>
                <Text style={styles.textInfo}>{rowData.goodsInfo}</Text>
            </View>
        )
    }

    componentDidMount() {
        this.getAllGoods()
    }
    renderNavBar() {
        return (
            <View style={styles.navBarStyle}>
                <View style={{width:(width-10)/3}}>
                    <TouchableOpacity onPress={()=>this.open()}>
                        <Text style={{color:'white'}} numberOfLines={1} >{this.state.city}</Text>
                    </TouchableOpacity>
                </View>
                <Text style={styles.topInputStyle}>Call酒么</Text>
                <View style={styles.navImageStyle}>
                    <TouchableOpacity onPress={this._focus1}>
                        <Icon name="search" size={15} color="white"/>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }
    open(){
        Picker.init({
            pickerConfirmBtnText:'确定',
            pickerCancelBtnText:'取消',
            pickerTitleText:'位置',
            pickerData: this._createAreaData(),
            selectedValue: ['广西', '南宁', '青秀区'],
            onPickerConfirm: pickedValue => {
                // console.log('area', pickedValue);
                this.setState({city:pickedValue});
            },
            onPickerCancel: pickedValue => {
                // console.log('area', pickedValue);
            },
            onPickerSelect: pickedValue => {
                //Picker.select(['广西', '南宁', '青秀区'])
                // console.log('area', pickedValue);
            }
        });
        Picker.show();
    }
    _createAreaData() {
        let data = [];
        let len = area.length;
        for(let i=0;i<len;i++){
            let city = [];
            for(let j=0,cityLen=area[i]['city'].length;j<cityLen;j++){
                let _city = {};
                _city[area[i]['city'][j]['name']] = area[i]['city'][j]['area'];
                city.push(_city);
            }

            let _data = {};
            _data[area[i]['name']] = city;
            data.push(_data);
        }
        return data;
    }
    _focus1(){
        this._setModalVisible(true)
    }
    _closeModal(){
        this._setModalVisible(false)
    }
    _setModalVisible(isVisible){
        this.setState({
            modalVisible:isVisible
        })
    }


    //获取GridView的数据
    _onFetch(pageNo, success, failure) {
        //方便测试空数据情况
        setTimeout(()=> {
            if (pageNo === 3) {
                success([]);
                return;
            }
            fetch(this.props.api_url)
                .then((response) => response.json())
                .then((responseData) => {
                    let data = Mock.mock(responseData);
                    if (data.success) {
                        let items = data.data;
                        success(items)
                    }
                })
                .catch((error) => {
                    failure('加载失败', null)
                })
        },3000)
    }

    //EasyGridView底部视图
    //当没有更多数据的时候
    renderFooterNoMore(){
        return(
            <View style={{paddingBottom:120,paddingTop:20}}>
                <Text style={{ textAlign:'center'}}>没有更多了</Text>
            </View>
        )
    }
    //当加载出错的时候
    renderFooterError(){
        return(
            <View style={{paddingBottom:120,paddingTop:20}}>
                <Text style={{ textAlign:'center'}}>加载出错</Text>
            </View>
        )
    }
    //当正在加载的时候
    renderFooterLoading(){
        return(
            <View style={{paddingBottom:120,paddingTop:20,flexDirection:'row',justifyContent:'center',alignItems:'center'}}>
                <LinesLoader size={10}/>
                <Text style={{ textAlign:'center'}}>正在加载</Text>
            </View>
        )
    }

    openComment(componentName,param) {
        const { navigate } = this.props.navigation;
        navigate(componentName,param)
    }

}
Home.propTypes = {
    api_url: React.PropTypes.string
};
Home.defaultProps = {
    api_url: 'http://rapapi.org/mockjs/18259/api/getYouLike?userId=456'
};
const styles = StyleSheet.create({
    container: {
        flex:1,
        backgroundColor:'#D8D8D8'
    },
    imageStyle: {
        width: (width-26)/2,
        height: (width-26)/2
    },
    listViewStyle: {
        backgroundColor: 'white',
        borderBottomColor: '#e8e8e8',
        borderBottomWidth: 0.5,
        overflow:'hidden',
        padding:5
    },

    textInfo:{
        position: 'absolute',
        left: 5,
        top: 5,
        backgroundColor: 'red',
        color: 'white',
        padding: 2,
    },
    navBarStyle: {
        height: Platform.OS == 'ios' ? 64 : 44,
        backgroundColor: 'rgba(255,96,0,1.0)',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        width:width,
        padding:5
    },
    topInputStyle: {
        textAlign:'center',
        color:'white',
        fontSize:16,
        fontWeight:'bold',
        width:(width-10)/3,
    },
    navImageStyle: {
        flexDirection: 'row',
        alignItems: 'center',
        width:(width-10)/3,
        justifyContent:'flex-end'
    },
});

